package servlet;

import dao.UsersManager;
import security.Irreversible;
import security.MD5Hex;
import service.AccountService;
import top.ConfigCenter;
import util.ServerResponse;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(name = "userInfoServlet", urlPatterns = "*.userInfoService", loadOnStartup = 0)
public class UserInfoServlet extends HttpServlet {

    private static AccountService accountService = ConfigCenter.getAccountService();
    private static Irreversible encrypter = new MD5Hex();

    @Override
    public void init() throws ServletException {
        try {
            Class.forName("top.ConfigCenter");
        } catch (ClassNotFoundException e) {
            System.err.println(e.getMessage());
            System.exit(-1);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");

        switch (req.getServletPath()) {
            case "/login.userInfoService":    doLogin(
                    req.getParameter("username"),
                    req.getParameter("password"),
                    req.getParameter("autolog"),
                    req.getContextPath() + "/main.jsp",
                    req.getContextPath() + "/login.jsp",
                    req.getSession(), resp);  break;
            case "/register.userInfoService": doRegist(req, resp); break;
            case "/logout.userInfoService":   doLogout(req, resp); break;
        }
    }

    public static void doLogin
    (String uname, String upass, String autoLogin, String succeedPage, String failPage, HttpSession session, HttpServletResponse resp)
    throws IOException {
        AccountService.LoginInfo logInfo = accountService.login(uname, upass);
        session.setAttribute("OESloginInfo", logInfo);

        if(logInfo.getLoginState() != AccountService.LoginState.SUCCEED) {
            clearCookies(resp);
            resp.sendRedirect(failPage);
            return;
        }

        if("true".equals(autoLogin)) {
            int lifeTime = Integer.parseInt(ConfigCenter.getAccountConfig("autoLogingLifeTime"));
            Cookie cookieAutoLogin   = new Cookie("OESloginAuto","true");
            Cookie cookieAutoLogName = new Cookie("OESloginName",uname);
            Cookie cookieAutoLogPass = new Cookie("OESloginPass",upass);
            cookieAutoLogin.setMaxAge(lifeTime);
            cookieAutoLogName.setMaxAge(lifeTime);
            cookieAutoLogPass.setMaxAge(lifeTime);
            resp.addCookie(cookieAutoLogin);
            resp.addCookie(cookieAutoLogName);
            resp.addCookie(cookieAutoLogPass);
        } else if("cancel".equals(autoLogin)) clearCookies(resp);

        resp.sendRedirect(succeedPage);
    }

    private static void doRegist(HttpServletRequest req, HttpServletResponse resp) throws IOException  {

        String uname = req.getParameter("username");
        String upass = req.getParameter("password");
        String unick = req.getParameter("usernick");

        UsersManager.UserDAOOptionResult res = accountService.register(uname, upass, unick);

        HttpSession session = req.getSession();
        session.setAttribute("OEStoreRegisterInfo", res);

        if(res == UsersManager.UserDAOOptionResult.SUCCEED) {
            doLogin(
                uname, upass, "cancel",
    req.getContextPath() + "/main.jsp",
        req.getContextPath() + "/login.jsp",
                req.getSession(), resp
            );
        } else resp.sendRedirect(req.getContextPath() + "/register.jsp");
    }

    private static void doLogout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        clearCookies(resp);
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath() + "/main.jsp");

    }

    private static void clearCookies(HttpServletResponse resp) {
        removeCookie("OESloginPass", resp);
        removeCookie("OESloginAuto", resp);
    }

    public static void removeCookie(String cookieName, HttpServletResponse resp) {
        Cookie clear = new Cookie(cookieName,null);
        clear.setMaxAge(0);
        resp.addCookie(clear);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        switch (req.getServletPath()) {
            case "/logout.userInfoService":   doLogout(req, resp); break;
            default: {
                ServerResponse sr = new ServerResponse(resp);
                //拒绝get账号请求
                sr.add("OESloginStat",         "fail");
                sr.add("OEStoreRegisterState", "fail_refusedGet");
                sr.commit();
            }
        }
    }

    /*
    public static void pageAutoLogin(String uname, String upass, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
        AccountService.LoginInfo logInfo = accountService.login(uname, upass);
        session.setAttribute("OESloginInfo", logInfo);

        if(logInfo.getLoginState() != AccountService.LoginState.SUCCEED) {
            removeCookie("OESloginAuto", response);
            removeCookie("OESloginPass", response);
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        } else response.sendRedirect(request.getContextPath() + "/main.jsp");
    }
    */
}
